<?php
/**
 * Created by PhpStorm.
 * User: luoqinghui
 * Date: 2020/7/24
 * Time: 上午17:40
 */

namespace App\Http\Controllers\Api\Diagnose;

use App\Modules\Bill\Models\Bill;
use App\Modules\Diagnose\Models\Graphic;
use App\Modules\Doctor\Services\DoctorService;
use App\Modules\User\Services\UserService;
use Illuminate\Support\Facades\Log;
use App\Modules\Order\Services\OrderService;
use App\Modules\Diagnose\Services\GraphicService;
use App\Modules\Diagnose\Services\OrderDiagnoseService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tencent\TLSSigAPIv2;

/**
 * 视频问诊
 * Class HomeController
 * @package App\Http\Controllers\Api\Home
 */
class CameraController extends Controller
{
    /**
     * 获取在线医生列表
     * @param Request $request
     * @return mixed
     */
    public function onlineDoctorsList(Request $request) {
       $doctor_ids = \Redis::sMembers('WebSocketOnlineDoctorIds');
       $doctors_list = DoctorService::getByAdminIds($doctor_ids);
       $doctor_online = array();
       $now = time();
        foreach ($doctors_list as $key=>$doctor) {
            //\Log::info('start_time:'.strtotime(date('Y-m-d '.$doctor->consultingTime->start_time.':s')));
            //\Log::info('end_time:'.strtotime(date('Y-m-d '.$doctor->consultingTime->end_time.':s')));
            # 把所有在线且在工作时间内的医生存进数组
            if($doctor->is_consulting && $doctor->consultingTime
                && $doctor->consultingTime->status==1 &&
                ($doctor->consultingTime->weeks_type == date('w') || $doctor->consultingTime->weeks_type == -1) &&
                strtotime(date('Y-m-d '.$doctor->consultingTime->start_time.':s')) <= $now &&
                strtotime(date('Y-m-d '.$doctor->consultingTime->end_time.':s')) > $now
            ) {
                $doctor->photo = env('APP_DOMAIN').$doctor->photo;
                array_push($doctor_online,$doctor);
            }
        }
       return response()->success($doctor_online);
    }

    /**
     * 视频问诊发起支付
     * @param Request $request
     * @return mixed
     */
    public function generate_camera_order(Request $request) {
        $pay_type = $request->input('pay_type',''); //coin,money
        //$doctor_id = $request->input('doctor_id','');
        $uid = $this->getLoginUserId();
        $payment_source = $request->input('payment_source','');

        if(empty($pay_type)||empty($payment_source)) {
            return response()->error('PARAM_EMPTY');
        }
        if(!in_array($pay_type,['coin','money']) ||
            !in_array($payment_source,['MINI_WECHAT','WECHAT','ALIPAY'])
        ) {
            return response()->error('PARAM_ERROR');
        }
        $not_used_order = OrderDiagnoseService::getUserPaidNotUsed($uid,1);
        if(!empty($not_used_order)) {
            return response()->error('EXIST_NOT_USED_ORDER');
        }
        switch ($pay_type) {
            case 'coin':$pay_type=2;break;
            case 'money':$pay_type=1;break;
        }
        $price_coin = 3000; //TODO 修改金币总额
        $price_money = 0.01;//TODO 修改总额
        \DB::beginTransaction();
        try{
            # 生成订单号
            $rand_num = mt_rand(0,9999);
            $trade_no = date('YmdHis').str_pad($rand_num,4-strlen($rand_num),'0',STR_PAD_LEFT);

            $diagnose_data = [
                'user_id'=>$uid,
                'type'=>1,
                'duration'=>0,
            ];
            $diagnose=Graphic::create($diagnose_data);

            $diagnose_order = [
                'trade_no'=>$trade_no,
                'user_id'=>$uid,
                'diagnose_id'=>$diagnose->id,
                'type'=>$pay_type,
                'amount'=>$pay_type==1?$price_money:$price_coin, //TODO 修改金额
                'payment_source'=>$payment_source,
                'pay_time'=>date('Y-m-d H:i:s'),
                'create_ip'=>$request->ip(),
                'diagnose_type'=>1
            ];
            OrderDiagnoseService::add($diagnose_order);
            if($pay_type == 1) {
                # 统一下单
                $pay_data = array(
                    'price'=>$price_money*100,//$sum_price * 100, //TODO 修改金额
                    'create_ip'=> $request->getClientIp(),
                    'openid'=> $this->getLoginUserWechatOpenId(),
                    'body' => '视频问诊',
                    'detail' => '视频问诊',
                    'trade_no' => $trade_no,
                    'remark' => '',
                    'notify_url' => env('VIDEO_DIAGNOSE_NOTIFY'),
                );
                //\Log::info($pay_data);
                $payResultInfo = OrderService::create_unpay($pay_data);
                $payResultInfo['order'] = $trade_no;
                \DB::commit();
                return response()->success($payResultInfo);
            }else{
                $user_info = UserService::getById($uid);
                if($user_info->balance < $price_coin) {
                    \DB::rollBack();
                    return response()->error('COIN_NOT_SUFFICIENT');
                }
                $user_info->balance = $user_info->balance - $price_coin;
                $user_info->save();
                \DB::commit();
                return response()->success();
            }

        }catch (\Exception $e) {
            \Log::error('video diagnose generate order failed:'.$e->getMessage());
            \DB::rollBack();
            return response()->error('PAID_FAILED');
        }


    }

    /**
     * 获取已支付未使用的订单
     * @param Request $request
     * @return mixed
     */
    public function getUserPaidNotUsedOrder(Request $request) {
        $uid = $this->getLoginUserId();
        $not_used_order = OrderDiagnoseService::getUserPaidNotUsed($uid,1);
        return response()->success($not_used_order);
    }

    /**
     * 获取视频通话TRTC功能 用户签名
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function genTrtcUserSgin(Request $request) {
        $userId = $request->input('user_id','');
        $api = new TLSSigAPIv2(env('TECENT_TRTC_APPID'), env('TENCENT_TRTC_SECRET'));
        $sig = $api->genSig($userId,604800);
        return response()->success([
            'userSgin'=>$sig,
            'sdkAppid'=>env('TECENT_TRTC_APPID')
        ]);
    }
}
























